<template>
  <div class="map-container">
    <div id="cesiumContainer"></div>

    <!-- 加载指示器 -->
    <div class="loading-indicator" v-if="isLoading">
      <div class="spinner"></div>
      <div class="loading-text">正在加载模型 ({{ loadingProgress }}%)</div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted } from "vue";
import { SupermapModel } from "./supermapModal";
import { eventBus } from "../../../plugins/eventBus";
import { getTunnelList } from "@/api"; // 导入隧道API
// 导入隧道图标资源
import tunnelGroupIcon from "@/assets/image/TunnelOverviewPanel/按钮样式07.png";
import singleTunnelIcon from "@/assets/image/TunnelOverviewPanel/按钮样式07 拷贝.png";

// 声明模型控制函数
const modelControl = ref(null);
const isLoading = ref(false);
const loadingProgress = ref(0);
const preloadedData = ref({});
let viewer = null;
const tunnelDataLoaded = ref(false);

// 设置加载进度
const setLoadingProgress = (progress) => {
  loadingProgress.value = Math.min(100, Math.max(0, progress));
};

// 显示加载指示器
const showLoading = () => {
  isLoading.value = true;
  loadingProgress.value = 0;
};

// 隐藏加载指示器
const hideLoading = () => {
  isLoading.value = false;
  loadingProgress.value = 100;
};

// 切换指定模型显示状态
const toggleModel = (index) => {
  if (modelControl.value) {
    const result = modelControl.value.toggleModel(index);
    console.log(`切换模型 ${index} 显示状态，当前状态:`, result);
    return result;
  }
  console.log(`模型控制器不存在，无法切换模型 ${index}`);
  return false;
};

// 切换所有模型显示状态
const toggleAllModels = () => {
  if (modelControl.value) {
    return modelControl.value.toggleAllModels();
  }
};

// 加载隧道标记
const loadTunnelMarkers = async () => {
  // 即使已经加载过，也允许重新加载
  if (!modelControl.value) return false;
  
  // 添加防重复加载锁
  if (loadTunnelMarkers.isLoading) {
    console.log("隧道标记正在加载中，请稍后再试");
    return false;
  }
  
  loadTunnelMarkers.isLoading = true;
  
  try {
    console.log("加载隧道标记...");
    
    // 显示加载指示器
    showLoading();
    setLoadingProgress(10);
    
    // 调用API获取隧道数据
    const response = await getTunnelList();
    setLoadingProgress(50);
    
    let tunnelData = [];
    
    // 处理API返回的数据
    if (response && response.code === 200 && Array.isArray(response.data)) {
      tunnelData = response.data
        .filter(item => {
          // 过滤掉无效数据
          const lng = Number(item.lng);
          const lat = Number(item.lat);
          if (isNaN(lng) || isNaN(lat) || !isFinite(lng) || !isFinite(lat)) {
            console.error(`过滤掉无效坐标的隧道: ${item.mapName || "未命名"} [${item.lng}, ${item.lat}]`);
            return false;
          }
          return true;
        })
        .map(item => {
          // 转换为隧道标记需要的数据格式
          let lng = Number(item.lng);
          let lat = Number(item.lat);
          
          // 检查坐标是否需要互换
          if ((lng < -180 || lng > 180 || lat < -90 || lat > 90) && 
              lat >= -180 && lat <= 180 && lng >= -90 && lng <= 90) {
            [lng, lat] = [lat, lng];
          }
          
          return {
            id: item.mapId,
            name: item.mapName,
            position: [lng, lat, 300], // 添加高度300米
            tunnelType: item.tunnelType || "隧道",
            cameras: item.cameras || 0,
            events: item.events || 0
          };
        });
    }
    
    setLoadingProgress(80);
    
    // 如果没有有效数据，使用备用数据
    if (!tunnelData.length) {
      console.log("使用备用隧道数据");
      tunnelData = [
        { id: 1, name: "石门隧道", position: [106.45, 29.57, 300], cameras: 5, events: 0 },
        { id: 2, name: "朝阳隧道", position: [106.31, 29.52, 300], cameras: 3, events: 1 },
        { id: 3, name: "双福隧道", position: [106.28, 29.4, 300], cameras: 6, events: 0 },
        { id: 4, name: "铜锣隧道", position: [106.15, 29.2, 300], cameras: 4, events: 1 },
        { id: 5, name: "永川隧道", position: [105.927, 29.356, 300], cameras: 7, events: 2 },
      ];
    }
    
    // 调用SupermapModel中的方法添加隧道标记
    const result = modelControl.value.addTunnelMarkers(tunnelData, {
      singleTunnelImageUrl: singleTunnelIcon,
      tunnelGroupImageUrl: tunnelGroupIcon,
      billboardScale: 1.3, // 增大图标比例以容纳文字
      heightOffset: 300, // 标记高度偏移
      labelOffset: new Cesium.Cartesian2(25, -84), // 调整文字位置，固定在图片内部
      labelHorizontalOrigin: Cesium.HorizontalOrigin.RIGHT, // 右对齐
      labelVerticalOrigin: Cesium.VerticalOrigin.CENTER, // 垂直居中对齐
      maxLabelChars: 100, // 显示完整文字，不使用省略号
      useCustomRendering: true // 使用自定义渲染方式
    });
    
    tunnelDataLoaded.value = result;
    console.log(`隧道标记加载${result ? '成功' : '失败'}, 共 ${tunnelData.length} 个隧道`);
    
    setLoadingProgress(100);
    hideLoading();
    
    loadTunnelMarkers.isLoading = false;
    return result;
  } catch (error) {
    console.error("加载隧道标记失败:", error);
    hideLoading();
    loadTunnelMarkers.isLoading = false;
    return false;
  }
};

// 预加载设备概况所需资源
const prepareDeviceOverview = async () => {
  if (!modelControl.value) return false;

  showLoading();
  console.log("开始准备设备概况视图...");

  try {
    // 确保所有模型可见
    if (modelControl.value.showAllModels) {
      modelControl.value.showAllModels();
    } else {
      // 如果方法不存在，使用toggleAllModels替代
      modelControl.value.toggleAllModels(true);
    }

    // 优化飞行速度和路径
    if (viewer) {
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          106.10745,
          29.15494,
          29065.38
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-45),
          roll: 0,
        },
        duration: 1.2, // 加快飞行速度，默认是3秒
        maximumHeight: 35000, // 控制最大飞行高度，避免飞得太高
        complete: () => {
          console.log("相机飞行完成");
          // 直接加载隧道标记，不需要等待回调
          loadTunnelMarkers();
          hideLoading();
        },
        cancel: () => {
          console.log("相机飞行取消");
          // 即使飞行取消也加载隧道标记
          loadTunnelMarkers();
          hideLoading();
        },
      });
    } else {
      // 如果viewer不存在也尝试加载隧道标记
      loadTunnelMarkers();
      hideLoading();
    }

    return true;
  } catch (error) {
    console.error("准备设备概况视图失败:", error);
    // 即使发生错误也尝试加载隧道标记
    loadTunnelMarkers();
    hideLoading();
    return false;
  }
};

// 道路模型控制（控制第一个和第三个模型）
const roadModalControl = () => {
  if (modelControl.value) {
    // 切换第一个模型的显示状态 (73行加载的模型)
    toggleModel(0);
    // 切换第三个模型的显示状态 (89行加载的模型)
    toggleModel(2);
    console.log("切换道路模型状态：", {
      model0: modelControl.value.getModelVisibility(0),
      model2: modelControl.value.getModelVisibility(2),
    });
    return true;
  }
  return false;
};

// 倾斜摄影模型控制（控制第二个模型）
const qxModalControl = () => {
  if (modelControl.value) {
    // 切换第二个模型的显示状态 (78行加载的模型)
    toggleModel(1);
    console.log("切换倾斜模型状态：", modelControl.value.getModelVisibility(1));
    return true;
  }
  return false;
};

// 添加性能监控
const startPerformanceMeasure = (name) => {
  if (window.performance) {
    window.performance.mark(`${name}-start`);
  }
};

const endPerformanceMeasure = (name) => {
  if (window.performance) {
    window.performance.mark(`${name}-end`);
    window.performance.measure(name, `${name}-start`, `${name}-end`);
    const measures = window.performance.getEntriesByName(name);
    if (measures.length > 0) {
      console.log(`${name} 性能测量:`, measures[0].duration.toFixed(2), "ms");
    }
    window.performance.clearMarks(`${name}-start`);
    window.performance.clearMarks(`${name}-end`);
    window.performance.clearMeasures(name);
  }
};

onMounted(async () => {
  try {
    // 开始性能测量
    startPerformanceMeasure("viewer-initialization");

    // 显示加载指示器
    showLoading();

    // 初始化Cesium Viewer
    viewer = new Cesium.Viewer("cesiumContainer", {
      infoBox: false,
      selectionIndicator: false,
      fullscreenButton: false,
      baseLayerPicker: false,
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      navigationHelpButton: false,
      animation: false,
      timeline: false,
      shouldAnimate: true,
      // 提高性能的配置
      requestRenderMode: true, // 仅在需要时才渲染场景
      maximumRenderTimeChange: Infinity, // 避免频繁渲染
    });

    // 提高渲染质量设置
    if (viewer && viewer.scene) {
      // 启用抗锯齿
      if (viewer.scene.postProcessStages && viewer.scene.postProcessStages.fxaa) {
        viewer.scene.postProcessStages.fxaa.enabled = true;
      }
      
      // 调整深度缓冲区设置，改善Z-fighting
      viewer.scene.logarithmicDepthBuffer = true;
    }

    // 结束性能测量
    endPerformanceMeasure("viewer-initialization");
    setLoadingProgress(20);

    // 开始测量底图加载性能
    startPerformanceMeasure("imagery-loading");

    // 使用高德地图作为底图
    const imageryProvider = new Cesium.UrlTemplateImageryProvider({
      url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
      // 优化图层加载
      maximumLevel: 18,
      enablePickFeatures: false,
    });
    viewer.imageryLayers.addImageryProvider(imageryProvider);

    // 添加另一图层
    const customImageryProvider = new Cesium.UrlTemplateImageryProvider({
      url: "http://10.1.0.48:9004/tile/image/wmts/krBB6Wek/{z}/{x}/{y}",
      maximumLevel: 18,
      enablePickFeatures: false,
    });
    viewer.imageryLayers.addImageryProvider(customImageryProvider);

    // 结束底图加载测量
    endPerformanceMeasure("imagery-loading");
    setLoadingProgress(40);

    // 开始测量地形加载性能
    startPerformanceMeasure("terrain-loading");

    // 加载地形
    const terrainProvider = await Cesium.CesiumTerrainProvider.fromUrl(
      "http://10.1.0.48:9004/tile/terrain/3fYe0qoB",
      {
        requestVertexNormals: false,
        // 地形优化
        requestWaterMask: false,
      }
    );
    viewer.terrainProvider = terrainProvider;

    // 结束地形加载测量
    endPerformanceMeasure("terrain-loading");
    setLoadingProgress(60);

    // 初始化模型管理器
    modelControl.value = new SupermapModel(viewer);

    setLoadingProgress(70);

    // 开始测量模型加载性能
    startPerformanceMeasure("model-loading");

    // 加载第一个模型
    await modelControl.value.loadModel(
      "http://10.1.0.48:9004/tile/model/service/RsfQLJja/tileset.json?labtoken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiItMSxUaHUgQXByIDE4IDE1OjMwOjU3IENTVCAyMDI0In0.j_YKsCRsIQtpgOWfFvMwAP65Rlx9uXyVte_xkE95Vdo",
      [
        0.9999999999999994, -2.3403894128248837e-8, -2.30305899767691e-8, 0,
        2.340389593236125e-8, 0.9999999999999967, 7.908582122517771e-8, 0,
        2.3030588131023322e-8, -7.908582183580037e-8, 0.9999999999999966, 0,
        -3.6582344139460474, 12.562183515168726, 7.33250831766054, 1,
      ]
    );
    setLoadingProgress(80);

    // 加载第二个模型
    await modelControl.value.loadModel(
      "http://10.1.0.48:9004/tile/model/service/k1YTLS4O/tileset.json",
      [
        1, 1.6653345369377348e-16, -1.1276721292863279e-8, 0,
        2.7755575615628914e-16, 0.9999999999999993, 3.9050056799272426e-8, 0,
        1.1276721278985491e-8, -3.905005685478358e-8, 0.9999999999999993, 0,
        -21.786347032291815, 75.44374545384198, 43.97191964043304, 1,
      ]
    );
    setLoadingProgress(90);

    // 加载第三个模型
    await modelControl.value.loadModel(
      "http://10.1.0.48:9004/tile/model/service/RsfQLJja/tileset.json?labtoken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiItMSxUaHUgQXByIDE4IDE1OjMwOjU3IENTVCAyMDI0In0.j_YKsCRsIQtpgOWfFvMwAP65Rlx9uXyVte_xkE95Vdo",
      [
        1, 0, -1.8895028042198447e-9, 0, -2.7755575615628914e-17, 1,
        6.4884522199548655e-9, 0, 1.8895028180976325e-9, -6.4884522199548655e-9,
        1, 0, -3.658341220812872, 12.562549189664423, 7.334647212643176, 1,
      ]
    );

    setLoadingProgress(95);

    // 设置相机视角 - 优化飞行速度
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(106.10745, 29.15494, 29065.38),
      orientation: {
        heading: Cesium.Math.toRadians(0),
        pitch: Cesium.Math.toRadians(-45),
        roll: 0,
      },
      duration: 1.5, // 加快飞行速度
      complete: () => {
        // 结束模型加载测量
        endPerformanceMeasure("model-loading");
        hideLoading();
      },
    });

    // 添加事件监听器
    eventBus.on("toggle-high-precision", handleHighPrecisionToggle);
    eventBus.on("toggle-oblique", handleObliqueToggle);
    eventBus.on("prepare-device-overview", handlePrepareDeviceOverview);
    console.log("事件监听器已添加");

    // 添加场景优化
    viewer.scene.logarithmicDepthBuffer = true; // 改善深度缓冲区精度
    console.timeEnd("initializeModel");
  } catch (error) {
    console.error("初始化失败:", error);
    hideLoading();
    throw Error(error);
  }
});

// 监听事件总线事件
const handleHighPrecisionToggle = () => {
  console.log("接收到高精模型切换事件");
  qxModalControl();
};

const handleObliqueToggle = () => {
  console.log("接收到倾斜模型切换事件");
  roadModalControl();
};

// 处理设备概况预加载请求
const handlePrepareDeviceOverview = () => {
  console.log("接收到设备概况预加载请求");
  prepareDeviceOverview()
    .then((result) => {
      console.log("设备概况预加载完成", result);
    })
    .catch((error) => {
      console.error("设备概况预加载失败", error);
    });
};

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  eventBus.off("toggle-high-precision", handleHighPrecisionToggle);
  eventBus.off("toggle-oblique", handleObliqueToggle);
  eventBus.off("prepare-device-overview", handlePrepareDeviceOverview);
});

// 关键：通过defineExpose暴露方法给父组件
defineExpose({
  roadModalControl,
  qxModalControl,
  prepareDeviceOverview,
  loadTunnelMarkers,  // 添加隧道标记方法
});
</script>

<style lang="scss" scoped>
/* 重置全局样式 */
html,
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

.map-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;

  #cesiumContainer {
    width: 100%;
    height: 100%;
  }
}

.loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 20px;
  border-radius: 8px;
  z-index: 1000;
}

.spinner {
  border: 5px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top: 5px solid #00ffff;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  font-size: 16px;
  font-weight: bold;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.control-buttons {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 100;
  display: flex;
  flex-direction: column;
  gap: 10px;

  button {
    padding: 8px 12px;
    background-color: rgba(255, 255, 255, 0.8);
    border: 1px solid #ccc;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      background-color: white;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }
  }
}

/* 隐藏Cesium自带的水印和按钮 */
:global(.cesium-viewer-bottom) {
  display: none !important;
}

:global(.cesium-viewer-toolbar) {
  display: none !important;
}

:global(.cesium-widget-credits) {
  display: none !important;
}
</style>
